package com.camic.core.loader
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	
	public class XLoader extends Loader
	{
		private var m_bLoading:Boolean = false;
		
		public function XLoader()
		{
			super();
		}
		
		public function isLoading():Boolean {
			return m_bLoading;
		}
		
		public function destroy():void {
			unload();
		}
		
		override public function load(request:URLRequest, context:LoaderContext=null):void {
			m_bLoading = true;
			addEventListeners();
			super.load(request, context);
		}
		
		override public function loadBytes(bytes:ByteArray, context:LoaderContext=null):void {
			m_bLoading = true;
			addEventListeners();
			super.loadBytes(bytes, context);
		}
		
		override public function unload():void {
			close();
			super.unload();
		}
		
		override public function close():void {
			if (isLoading()) {
				removeEventListeners();
				m_bLoading = false;
				super.close();
			}
		}
		
		private function addEventListeners():void {
			contentLoaderInfo.addEventListener(Event.COMPLETE, __OnComplete, false, 100);
			contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, __OnIOError, false, 100);
		}
		private function removeEventListeners():void {
			contentLoaderInfo.removeEventListener(Event.COMPLETE, __OnComplete);
			contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, __OnIOError);
		}
		
		private function __OnComplete(e:Event):void {
			m_bLoading = false;
			removeEventListeners();
		}
		
		private function __OnIOError(e:IOErrorEvent):void {
			m_bLoading = false;
			removeEventListeners();
		}
	}
}